package com.example.scaletest.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.example.scaletest.bean.BindData;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LK on 2016/10/19.
 */
public class DataDao {
    private Context context;
    private DataBaseHelper dbHelper;
    private static volatile DataDao instance = null;
    private DataDao(Context context){
        this.context = context;
        dbHelper = DataBaseHelper.getInstance(context);

    }

    public static DataDao getInstance(Context context){
        if (instance == null){
            synchronized (DataDao.class){
                if (instance == null){
                    instance = new DataDao(context);
                }
            }
        }
        return instance;
    }

    public void addBindData(BindData bindData){
        synchronized (this){
            SQLiteDatabase db = dbHelper.open();
            ContentValues values = new ContentValues();
            values.put(DataBaseHelper.BATCH_ID,bindData.getBatchId());
            values.put(DataBaseHelper.DEVICE_ID,bindData.getDeviceId());
            values.put(DataBaseHelper.GOODS_ID,bindData.getGoodsId());
            db.insert(DataBaseHelper.T_INFO, null, values);
            dbHelper.close();
        }
    }

    public List<BindData> getBindData(){
        List<BindData> result = new ArrayList<>();
        synchronized (this){
            SQLiteDatabase db = dbHelper.open();
            Cursor cursor = db.query(DataBaseHelper.T_INFO,null,null,null,null,null,null);
            while (cursor.moveToNext()){
                BindData bindData = new BindData(cursor.getInt(0),cursor.getString(1),
                        cursor.getString(2),cursor.getString(3));
                result.add(bindData);
            }
        }
        return result;
    }

    public void deleteBindData(){
        synchronized (this){
            SQLiteDatabase db = dbHelper.open();
            db.delete(DataBaseHelper.T_INFO,null,null);
            db.close();
        }
    }
}
